<!--
*@Author: QWP
*@Description: 公文编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog
    v-bind="$attrs"
    destroyOnClose
    :confirmLoading="loading"
    :hideBtns="isCheck ? ['submit'] : []"
    :beforeClose="beforeClose"
    @close="dialogClose"
    @submit="submit">
    <u-flow-tab
      activeKey="1"
      :show="isValue(form.status)"
      :params="{ type: 'official_doc_dispatch', ...current }"
      :isAudit="form.status == 2"
      :isAuditPage="route.params.pType == '2'"
      v-bind="$attrs"
      ref="auditRef"
      @back="getAuditData">
      <a-tab-pane
        key="1"
        tab="基本信息">
        <a-row
          :gutter="12"
          class="f-w-100">
          <a-col :span="24">
            <u-form
              :elements="formEls"
              :model="form"
              :gutter="0"
              :loading="loading"
              :disabled="isCheck"
              ref="formRef"
              class="u-doc-draft-form">
              <template #zw>
                <a-input-group compact>
                  <a-input
                    v-model:value="form.zw"
                    style="width: calc(100% - 32px)" />
                  <a-button>
                    <template #icon>
                      <PlusOutlined />
                    </template>
                  </a-button>
                </a-input-group>
              </template>
              <template #xgwd>
                <a-input-group compact>
                  <a-input
                    v-model:value="form.xgwd"
                    style="width: calc(100% - 32px)" />
                  <a-button>
                    <template #icon>
                      <PlusOutlined />
                    </template>
                  </a-button>
                </a-input-group>
              </template>
              <template #fileNoChar>
                <a-input-group compact>
                  <a-select
                    v-model:value="form.fileNoChar"
                    :options="fileNoChars"
                    style="width: calc(50% - 38px)" />
                  <div style="height: 32px; line-height: 32px">〔 {{ form.fileNoYear }} 〕</div>
                  <a-form-item-rest>
                    <a-input
                      v-model:value="form.fileNoOrder"
                      addonAfter="号"
                      :maxlength="4"
                      style="width: calc(50% - 38px)"
                      id="fileNoOrder" />
                  </a-form-item-rest>
                </a-input-group>
              </template>
            </u-form>
          </a-col>

          <div class="u-doc-loading">
            <a-spin
              tip="文档保存中..."
              :spinning="loadingDoc">
              <u-doc-editor
                :current="{ ...form, ...(form.fileList || [{}])[0] }"
                v-if="loadingDoc == false"
                reduceH="100px"
                class="f-margin-t16"
                @change="isChangeDoc = true" />
            </a-spin>
          </div>
        </a-row>
      </a-tab-pane>
    </u-flow-tab>
    <template #footerBefore>
      <template v-if="!form['status'] || ['1', '4'].includes(form['status'] + '')">
        <u-icon-button
          itype="save"
          @click="submit('up')"
          :loading="loading">
          保存并上报
        </u-icon-button>
      </template>
      <template v-if="route.params.pType == '2' && form['status'] == '2' && isAudited == true">
        <u-icon-button
          itype="approve"
          @click="auditAbout('2')">
          批准
        </u-icon-button>
        <u-icon-button
          itype="close"
          @click="auditAbout('3')">
          退回
        </u-icon-button>
        <!-- <u-icon-button itype="reansmit">转发</u-icon-button> -->
      </template>
    </template>
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, useAttrs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useBaseStore, useLoginStore } from "@/store";
import { storeToRefs } from "pinia";
import { _IFormEl } from "@/src/components/common/form/interface";
import { FormInstance, FormItemProps } from "ant-design-vue";
import { HomeOutlined, FileTextOutlined, UploadOutlined } from "@ant-design/icons-vue";
import SignAudit from "./SignAudit.vue";
import UIconFont from "@/components/common/iconfont/IconFont.vue";
import { isSel1 } from "@/common/model/base";
import { FileTypes } from "@/common/model/const";
import { nullC, alertC, messageC, sleep, isValue } from "@/util/common";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import * as unitApi from "@/service/system/unit";
import * as publishDocApi from "@/service/officialDoc/publishDoc";
import { cloneDeep } from "lodash";
import dayjs from "dayjs";

const props = defineProps<{
  current?: object;
  isAudited?: boolean;
}>();

const attrs = useAttrs();
const route = useRoute();
const { INC_NODE, EMERGENCY_DEGREE, OPEN_FORM, fileNoChars, unitData } = storeToRefs(useBaseStore());
const { userInfo } = storeToRefs(useLoginStore());

const emits = defineEmits(["success"]);

const isCheck = computed(() => ["2", "3"].includes(form.value.status + ""));

// 文档是否编辑
const isChangeDoc = ref<boolean>(false);
const loadingDoc = ref<boolean>(false);

// 表单
const loading = ref<boolean>(false);
const auditRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
const form = ref({
  fileNoYear: new Date().getFullYear(),
  incdocunitname: "",
});
const formItemProps: FormItemProps = {
  labelWidth: "140px",
  colon: false,
};
const formEls: Array<_IFormEl> = [
  // { label: '选择节点信息', key: 'taskname', col: { span: 8 }, element: 'select',
  //   formItemProps: { ...formItemProps, required: true } ,
  //   componentProps: { options: INC_NODE.value }
  // },
  {
    label: "签发",
    key: "qf",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "办公室核稿",
    key: "bgshg",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "相关部门会签",
    key: "xgbmhq",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "主办部门负责人",
    key: "zbbmfzr",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "主办部门",
    key: "redeptname",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "拟稿人",
    key: "username",
    col: { span: 8 },
    element: "text",
    formItemProps: { ...formItemProps, class: "u-view-text" },
  },
  {
    label: "标题",
    key: "title",
    col: { span: 24 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
    // componentProps: { bordered: false }
  },
  {
    label: "主送单位",
    key: "fkunitsid1",
    col: { span: 8 },
    element: "treeselect",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      suffix: h(UIconFont, { type: "icon-chaosongdanwei" }),
      treeData: unitData.value,
      fieldNames: { label: "name", value: "keyid" },
    },
  },
  {
    label: "抄送单位",
    key: "fkunitsid0",
    col: { span: 8 },
    element: "treeselect",
    formItemProps,
    componentProps: {
      suffix: h(UIconFont, { type: "icon-chaosongdanwei" }),
      treeData: unitData.value,
      fieldNames: { label: "name", value: "keyid" },
      multiple: true,
      resultType: "Array",
    },
  },
  {
    label: "发文单位",
    key: "incdocunitname",
    col: { span: 8 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
  },
  // { label: '经办人座机号码', key: 'handlenum', col: { span: 8 }, element: 'input',
  //   formItemProps: { ...formItemProps, required: true }
  // },
  // { label: '文件标题', key: 'fileTitle', col: { span: 8 }, element: 'input',
  //   formItemProps: { ...formItemProps, required: true }
  // },

  // { label: '正式文件下载', key: 'zswjxz', col: { span: 8 }, element: 'slot',
  //   formItemProps: { ...formItemProps, },
  // },
  {
    label: "文件编号",
    key: "fileNoChar",
    col: { span: 8 },
    element: "slot",
    formItemProps: { ...formItemProps, autoLink: false, required: true },
  },
  // { label: '文号', key: 'docnumber', col: { span: 8 }, element: 'input',
  //   formItemProps: { ...formItemProps, autoLink: false },
  // },
  {
    label: "紧急程度",
    key: "urgencyDegree",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps },
    componentProps: { options: EMERGENCY_DEGREE.value },
  },
  {
    label: "份数",
    key: "no",
    col: { span: 8 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: "公开形式",
    key: "openForm",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: OPEN_FORM.value },
  },
  {
    label: "是否涉密",
    key: "isSecretRelated",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: isSel1() },
  },
  {
    label: "规范性文件",
    key: "normaDoc",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps },
    componentProps: { options: isSel1() },
  },
  {
    label: "发文依据及目的",
    key: "byPurpose",
    col: { span: 24 },
    element: "input",
    formItemProps: { ...formItemProps },
  },
  {
    label: "正文摘要",
    key: "docabs",
    col: { span: 24 },
    element: "input",
    formItemProps: { ...formItemProps },
  },
  {
    label: "正文",
    key: "fileList",
    col: { span: 24 },
    element: "file", //'slot',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      accept: ".doc, .docx",
      fileParams: { biztype: "1", bucket: "INC", maxCount: 1, isEditor: 1 },
    },
  },
  {
    label: "附件",
    key: "fj",
    col: { span: 24 },
    element: "file",
    formItemProps: { ...formItemProps },
    componentProps: {
      fileParams: { biztype: "3", bucket: "INC" },
    },
  },
  {
    label: "相关文档",
    key: "xgwd",
    col: { span: 24 },
    element: "file",
    formItemProps: { ...formItemProps },
    // componentProps: {
    //   suffix: h(UIconFont, { type: 'icon-xiangguanwenjian' }),
    // }
    componentProps: {
      fileParams: { biztype: "2", bucket: "INC", maxCount: 1 },
    },
  },
  {
    label: "备注",
    key: "contents",
    col: { span: 24 },
    element: "textarea",
    formItemProps: { ...formItemProps },
  },
];

// 保存提交
const submit = async (type?: string): void => {
  try {
    await formRef.value.form.validate();
  } catch (error) {
    alertC("请先将表单信息填写完毕!");
    return;
  }

  if (!form.value["fileNoChar"] || !form.value["fileNoOrder"]) {
    alertC("请将文件编号填写完毕!");
    return;
  }

  const url = form.value.keyid ? "update" : "add";

  let filename = form.value["fileList"][0]["filename"].split(".");
  if (!FileTypes.word.includes(filename[filename.length - 1].toLocaleLowerCase())) {
    messageC("正文只能上传Word文件，请重新上传!");
    return;
  }

  const tForm = formatSubmit(cloneDeep(form.value));

  alertC("确认保存？", "confirm").then(async () => {
    loading.value = true;
    try {
      const res = await publishDocApi[url](tForm);
      if (res.code == 0) {
        if (type != "up") {
          messageC(res.msg, "success");
        }
        if (url == "add") {
          form.value.keyid = res.data["keyid"];
          form.value.status = res.data["status"];
        }
        if (type == "up") {
          await auditAbout("1");
        } else {
          dialogClose();
          emits("success");
        }
      } else {
        messageC(res.msg, "error");
      }
    } catch (error) {}
    loading.value = false;
  });
};

// 上报、审核、退回
const auditAbout = async (type: string) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: "official_doc_dispatch",
    selDatas: [form.value],
    confirm: false,
    isDialog: false,
  };
  try {
    const res = await useAuditAbout(type, auditParams, auditRef);
    if (res.error == 200) {
      dialogClose();
      emits("success");
    }
  } catch (error) {}
  loading.value = false;
};

// 格式化保存数据
const formatSubmit = (tForm) => {
  // stats  1 主送     0 抄送
  let acceptList1 = [];
  let unit1 = unitData.value.find((i) => i.keyid == tForm.fkunitsid1) || {};

  let unit1Info = {
    fkunitsid: tForm.fkunitsid1,
    reunitname: nullC(unit1["name"]),
    stats: 1,
  };
  acceptList1.push(unit1Info);

  // 抄送
  let acceptList0 = [];
  (form.value.fkunitsid0 || []).forEach((item) => {
    let unit0 = unitData.value.find((i) => i.keyid == item) || {};
    let unit0Info = {
      fkunitsid: item,
      reunitname: nullC(unit0["name"]),
      stats: 0,
    };
    acceptList0.push(unit0Info);
  });

  tForm.acceptList = [...acceptList1, ...acceptList0];

  delete tForm.fj;
  delete tForm.xgwd;
  delete tForm.fkunitsid0;

  // 正文
  tForm.fileList = [
    ...(form.value.fileList || []).map((item) => {
      return { ...item, fileAttribute: 1 };
    }),
    ...(form.value.fj || []).map((item) => {
      return { ...item, fileAttribute: 2 };
    }),
    ...(form.value.xgwd || []).map((item) => {
      return { ...item, fileAttribute: 3 };
    }),
  ];

  return tForm;
};

// 新增初始化元数据
const initFormInfo = () => {
  form.value = {
    fileNoYear: new Date().getFullYear(),
    incdocunitname: userInfo.value.unitName,
    fkunitsid: userInfo.value.unitId,
    fkdeptid: userInfo.value.deptId,
    redeptname: userInfo.value.deptName,
    username: userInfo.value.name,
    docType: 1, // 发文
  };
};

// 获取回显信息
const echoInfo = async () => {
  loading.value = true;
  try {
    const res = await publishDocApi.query(props.current["keyid"]);
    if (res.code == 0) {
      let data = res.data;
      form.value = res.data;
      form.value.fkunitsid0 = [];
      (data.acceptList || []).forEach((item) => {
        if (item.stats == 1) {
          form.value.fkunitsid1 = item.fkunitsid;
        } else {
          form.value.fkunitsid0.push(item.fkunitsid);
        }
      });

      let fileList = form.value["fileList"] || [];

      form.value.fileList = fileList.filter((i) => i.fileAttribute == 1);
      form.value.fj = fileList.filter((i) => i.fileAttribute == 2);
      form.value.xgwd = fileList.filter((i) => i.fileAttribute == 3);
      console.log("🚀 ~ echoInfo ~ form.value:", form.value);
    }
  } catch (error) {}
  loading.value = false;
};

// 获取签批信息
const getAuditData = (data: any[]) => {
  let result = {};
  data.forEach((item) => {
    if (!result[item["usertaskname"]]) {
      result[item["usertaskname"]] = [];
    }
    result[item["usertaskname"]].push(item);
  });

  const group = (items) => {
    let tRes = {};
    items.forEach((o) => {
      if (!tRes[o["username"]]) {
        tRes[o["username"]] = [];
      }
      tRes[o["username"]].push(o);
    });

    let aas = [];
    for (let k in tRes) {
      let kks = tRes[k] || [];
      let name = nullC(kks[kks.length == 0 ? 0 : kks.length - 1]["username"]);
      let msg = nullC(kks[kks.length == 0 ? 0 : kks.length - 1]["msg"]);
      // aas.push(name + (msg ? `(${msg})` : ''))
      aas.push(name);
    }

    return aas.join(",                                       ");
  };

  for (let key in result) {
    let tRes = result[key] || [];
    let current = formEls.find((i) => i.label == key);
    if (current) {
      form.value[current["key"]] = group(tRes);
    }
  }
};

// 弹窗关闭前
const beforeClose = () => {
  if (isChangeDoc.value == true) {
    loading.value = true;
    loadingDoc.value = true;
    return sleep(10000);
  }
};

// 弹窗关闭
const dialogClose = () => {
  formRef.value.form.resetFields();
  form.value = {};
};

watch(
  () => attrs.open,
  (nval, oval) => {
    if (nval == false) return;

    isChangeDoc.value = false;
    loadingDoc.value = false;

    if (props.current["keyid"]) {
      echoInfo();
    } else {
      initFormInfo();
    }
  }
);

watch(
  () => form.value.fileList,
  (nval, oval) => {
    if (!nval) return;

    if (nval.length > 1) {
      form.value.fileList = nval.splice(nval.length - 1, 1);
    }
    formRef.value.form.clearValidate(["fileList"]);
  },
  { deep: true }
);
</script>

<style lang="scss">
.u-doc-draft-form {
  & > .ant-row {
    $borderColor: #ea0000;
    border-bottom: 1px solid $borderColor;
    border-right: 1px solid $borderColor;

    .ant-form-item {
      margin-bottom: 0;
      height: 100%;

      .ant-form-item-row {
        height: 100%;

        & > .ant-col {
          border: 1px solid $borderColor;
          border-bottom: unset;
          border-right: unset;
          border-collapse: collapse;
          background: rgba(234, 0, 0, 0.05);

          :nth-child(n + 1) {
          }

          :nth-child(n + 2) {
            // background: #fff;
          }
        }

        .ant-form-item-label {
          label {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            color: #ea0000;
            line-height: 22px;
            text-align: left;
            font-style: normal;
            text-transform: none;
          }
        }

        .ant-form-item-control-input {
          height: 100%;
        }
      }

      .ant-input-suffix {
        color: #aaaaaa;
      }
    }

    .u-view-text {
      .ant-form-item-row {
        height: 60px;

        .ant-form-item-label {
          line-height: 60px;
        }
      }
    }
  }

  .ant-upload-list-item-container {
    .ant-col {
      border: none !important;
      background: unset !important;
    }
  }
}
.u-doc-loading {
  .ant-spin-container {
    width: calc(100vw - 62px);
    min-height: 400px;
  }
}
</style>
